import React,{useState,useEffect,} from 'react';
import { Button, Table, notification, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios'
const Nwespubish = (props) => {
  const { username } = JSON.parse(localStorage.getItem('token'))
  const [FromData,setFromDate] = useState([])
    useEffect(() => {
      axios.get(`/news?author=${username}&publishState=${props.publishType}&_expand=category`).then(res => {
        setFromDate(res.data)
      })
    },[username])
    const columns = [
     {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title,item) => {
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author'
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return category.title
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          {
            props.publishType === 1 &&  <Button type="primary" onClick={() => {
              release(item.id,2)
            }}>发布</Button>
          }
           {
            props.publishType === 2 &&  <Button type="primary" onClick={() => {
              release(item.id,3)
            }}>下线</Button>
          }
           {
            props.publishType === 3 &&  <Button danger onClick={() => {
              release(item.id)
            }}>删除</Button>
          }
        </div>
      }
    }
  ]
  // 发布
  const release = (id,num) => {
    setFromDate(FromData.filter(item => item.id !== id))
    if (num) {
      axios.patch(`/news/${id}`, {
        publishState: num,
        publishTime: Date.now()
      }).then(res => {
        notification.info({
          message: `通知`,
          description:`您可以在【发布管理/${num ===2? "已经发布":'已下线'}】中查看您的新闻`,
          placement:'bottomRight'
        });
      })
    } else {
      Modal.confirm({
      title: '删除',
      icon: <ExclamationCircleOutlined />,
      content: '你确认删除吗？',
      okText: '确认',
      cancelText: '取消',
        onOk() {
           axios.delete(`/news/${id}`)
        }
      })
    }
  }
  return (
    <div>
     <Table
        dataSource={FromData}
        columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={(item)=>item.id}
      ></Table>
    </div>
  );
}

export default Nwespubish;
